package com.jcfk.eam.service.base;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.DictionaryItemVo;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.base.EamSopItemDao;
import com.jcfk.eam.dao.base.EamSopStandardDao;
import com.jcfk.eam.domain.dto.base.*;
import com.jcfk.eam.domain.dto.main.EamPointCheckResultDTO;
import com.jcfk.eam.domain.po.base.EamSopItemValue;
import com.jcfk.eam.domain.po.base.EamSopStandard;
import com.jcfk.eam.domain.po.base.EamSopStandardImg;
import com.jcfk.eam.domain.po.main.EamPointCheckDetail;
import com.jcfk.eam.domain.po.main.EamPointCheckOrder;
import com.jcfk.eam.domain.query.base.EamSopItemQuery;
import com.jcfk.eam.domain.query.base.EamSopStandardQuery;
import com.jcfk.eam.service.main.EamPointCheckDetailService;
import com.jcfk.eam.service.main.EamPointCheckOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 标准作业规程
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-08-08
 */
@Service
public class EamSopStandardService extends BaseService<EamSopStandardDao, EamSopStandard> {

    @Autowired
    private EamSopStandardImgService eamSopStandardImgService;
    @Autowired
    private EamAssetTypeService eamAssetTypeService;
    @Autowired
    private EamSopTypeService eamSopTypeService;
    @Autowired
    private EamMakerService eamMakerService;
    @Autowired
    private EamAssetBrandService eamAssetBrandService;
    @Autowired
    private EamAssetModelService eamAssetModelService;
    @Autowired
    private EamSopItemDao eamSopItemDao;
    @Autowired
    private EamSopItemValueService eamSopItemValueService;
    @Autowired
    private EamPointCheckOrderService eamPointCheckOrderService;
    @Autowired
    private EamPointCheckDetailService eamPointCheckDetailService;


    /**
     * EamSopStandard分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamSopStandardDTO> queryByPage(DataPage<EamSopStandardDTO> page, EamSopStandardQuery query) {
        // 分页查询
        query.setStandardCode(StringUtils.isEmpty(query.getStandardCode()) ? query.getStandardCode() : query.getStandardCode() + "%");
        query.setStandardName(StringUtils.isEmpty(query.getStandardName()) ? query.getStandardName() : query.getStandardName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamSopStandard是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamSopStandardDTO dto) {
        QueryWrapper<EamSopStandard> queryWrapper = new QueryWrapper<>();
        if (dto.getAssetKind() != null && dto.getAssetKind() == 3) {
            queryWrapper.lambda().eq(EamSopStandard::getEquipTypeId, dto.getEquipTypeId());
        } else {
            queryWrapper.lambda().eq(EamSopStandard::getStandardCode, dto.getStandardCode());
        }
        queryWrapper.lambda().eq(EamSopStandard::getDeleted, 0);
        queryWrapper.lambda().eq(EamSopStandard::getSopTypeId, dto.getSopTypeId());
        queryWrapper.lambda().eq(EamSopStandard::getAssetKind, dto.getAssetKind());
        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        Integer count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("标准作业编号已存在");

        return RetResult.ok();
    }

    /**
     * 插入标准作业规程
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamSopStandardDTO dto) {

        // 保存
        EamSopStandard item = new EamSopStandard();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        List<EamSopStandardImg> files = new ArrayList<>();
        for (EamSopStandardImgDTO imgae : dto.getImages()) {
            EamSopStandardImg eamSopStandardImg = new EamSopStandardImg();
            eamSopStandardImg.setStandardId(item.getId());
            eamSopStandardImg.setUrl(imgae.getUrl());
            eamSopStandardImg.setFileType(imgae.getFileType());
            eamSopStandardImg.setFilename(imgae.getFilename());
            eamSopStandardImg.setOriginalfilename(imgae.getOriginalfilename());
            eamSopStandardImg.setPath(imgae.getPath());
            eamSopStandardImgService.setDefaultValue(eamSopStandardImg);
            files.add(eamSopStandardImg);
        }

        if (files.size() > 0) eamSopStandardImgService.saveBatch(files);

    }

    /**
     * 更新标准作业规程
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamSopStandardDTO dto) {

        // 保存
        EamSopStandard item = new EamSopStandard();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        QueryWrapper<EamSopStandardImg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamSopStandardImg::getStandardId, dto.getId());
        eamSopStandardImgService.remove(queryWrapper);

        List<EamSopStandardImg> files = new ArrayList<>();
        for (EamSopStandardImgDTO imgae : dto.getImages()) {
            EamSopStandardImg eamSopStandardImg = new EamSopStandardImg();
            eamSopStandardImg.setStandardId(item.getId());
            eamSopStandardImg.setUrl(imgae.getUrl());
            eamSopStandardImg.setFileType(imgae.getFileType());
            eamSopStandardImg.setFilename(imgae.getFilename());
            eamSopStandardImg.setOriginalfilename(imgae.getOriginalfilename());
            eamSopStandardImg.setPath(imgae.getPath());
            eamSopStandardImgService.setDefaultValue(eamSopStandardImg);
            files.add(eamSopStandardImg);
        }

        if (files.size() > 0) eamSopStandardImgService.saveBatch(files);
    }

    /**
     * 根据批量主键删除标准作业规程(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamSopStandardDTO dto) {

        EamSopStandard item = new EamSopStandard();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamSopStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamSopStandard item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取标准作业规程信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamSopStandardDTO get(String id) {
        // 查询数据
        EamSopStandard item = this.baseMapper.selectById(id);
        EamSopStandardDTO dto = new EamSopStandardDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        QueryWrapper<EamSopStandardImg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamSopStandardImg::getStandardId, dto.getId());
        List<EamSopStandardImg> list = eamSopStandardImgService.list(queryWrapper);
        dto.setImages(convertList(list, EamSopStandardImgDTO.class));

        if (StrUtil.isNotEmpty(dto.getEquipTypeId())) {
            EamAssetTypeDTO eamAssetTypeDTO = eamAssetTypeService.get(dto.getEquipTypeId());
            if (eamAssetTypeDTO != null) {
                dto.setAssetTypeCode(eamAssetTypeDTO.getAssetTypeCode());
                dto.setAssetTypeName(eamAssetTypeDTO.getAssetTypeName());
            }
        }

        EamSopTypeDTO eamSopTypeDTO = eamSopTypeService.get(dto.getSopTypeId());
        dto.setSopTypeName(eamSopTypeDTO.getSopTypeName());
        dto.setSopTypeCode(eamSopTypeDTO.getSopTypeCode());

        if (!StringUtils.isEmpty(dto.getAssetModelId())) {
            EamAssetModelDTO eamAssetModelDTO = eamAssetModelService.get(dto.getAssetModelId());
            dto.setModelNo(eamAssetModelDTO.getModelNo());
            EamMakerDTO eamMakerDTO = eamMakerService.get(eamAssetModelDTO.getMakerId());
            EamAssetBrandDTO eamAssetBrandDTO = eamAssetBrandService.get(eamAssetModelDTO.getBrandId());
            dto.setMakerCode(eamMakerDTO.getMakerCode());
            dto.setMakerName(eamMakerDTO.getMakerName());
            dto.setMakerId(eamMakerDTO.getId());

            dto.setBrandCode(eamAssetBrandDTO.getBrandCode());
            dto.setBrandId(eamAssetBrandDTO.getMakerId());
            dto.setBrandName(eamAssetBrandDTO.getMakerName());
        }
        return dto;
    }

    /**
     * 根据作业规程编号生成点检单
     *
     * @return StandardCodeDTO
     */
    public EamPointCheckResultDTO getSopStandard(String id) {

        if (StrUtil.isEmpty(id)) {
            throw new RuntimeException("标准不能为空");
        }

        // 查询获取标准作业
        EamSopStandardQuery query = new EamSopStandardQuery();
        query.setId(id);
        EamPointCheckResultDTO dto = this.baseMapper.getSopStandard(query);

        this.getSopStandard(dto);
        return dto;
    }

    /**
     * 根据作业规程编号生成点检单
     *
     * @return StandardCodeDTO
     */
    public EamPointCheckResultDTO getSopStandard(String sopTypeCode, String standardCode) {

        // 查询获取标准作业
        EamSopStandardQuery query = new EamSopStandardQuery();
        query.setSopTypeCode(sopTypeCode);
        query.setStandardCode(standardCode);
        EamPointCheckResultDTO dto = this.baseMapper.getSopStandard(query);

        if (dto == null) return null;

        this.getSopStandard(dto);
        return dto;
    }

    /**
     * 根据作业规程编号生成点检单
     *
     * @return StandardCodeDTO
     */
    public EamPointCheckResultDTO getSopStandard(String sopTypeCode, String assetTypeCode, String planId) {

        // 查询获取标准作业
        EamSopStandardQuery query = new EamSopStandardQuery();
        query.setSopTypeCode(sopTypeCode);
        query.setAssetTypeCode(assetTypeCode);
        EamPointCheckResultDTO dto = this.baseMapper.getSopStandard(query);

        if (dto == null) return null;

        this.getSopStandard(dto);
        // 查询点检单，看有没有结果值
        if (!StrUtil.isEmpty(planId)) {
            this.setSopStandardSaveValue(dto, planId);
        }
        return dto;
    }

    /**
     * 点检项查询结果值，有就赋予到saveValue
     */
    public EamPointCheckResultDTO setSopStandardSaveValue(EamPointCheckResultDTO dto, String planId) {
        QueryWrapper<EamPointCheckOrder> queryOrder = new QueryWrapper<>();
        queryOrder.lambda().eq(EamPointCheckOrder::getDeleted, 0);
        queryOrder.lambda().eq(EamPointCheckOrder::getPlanId, planId);
        queryOrder.lambda().orderByDesc(EamPointCheckOrder::getWorkTime);
        List<EamPointCheckOrder> eamPointCheckOrderList = eamPointCheckOrderService.list(queryOrder);
        if (eamPointCheckOrderList.size() == 0) {
            return dto;
        }
        EamPointCheckOrder eamPointCheckOrder = eamPointCheckOrderList.get(0);
        for (EamSopItemDTO eamSopItemDTO : dto.getItemDTOS()) {

            if ("1".equals(eamSopItemDTO.getStandardValue())) {
                // 测量值
                QueryWrapper<EamPointCheckDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(EamPointCheckDetail::getSopItemId, eamSopItemDTO.getId());
                queryWrapper.lambda().eq(EamPointCheckDetail::getOrderId, eamPointCheckOrder.getId());
                EamPointCheckDetail eamPointCheckDetail = eamPointCheckDetailService.getOne(queryWrapper);
                if (eamPointCheckDetail == null) {
                    continue;
                }
                eamSopItemDTO.setSaveValue(eamPointCheckDetail.getSopItemValue());
            } else {
                // 非测量值
                for (EamSopItemValueDTO eamSopItemValueDTO : eamSopItemDTO.getDetails()) {
                    QueryWrapper<EamPointCheckDetail> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(EamPointCheckDetail::getSopItemId, eamSopItemDTO.getId());
                    queryWrapper.lambda().eq(EamPointCheckDetail::getOrderId, eamPointCheckOrder.getId());
                    queryWrapper.lambda().eq(EamPointCheckDetail::getSopItemValueId, eamSopItemValueDTO.getId());
                    EamPointCheckDetail eamPointCheckDetail = eamPointCheckDetailService.getOne(queryWrapper);
                    if (eamPointCheckDetail == null) {
                        continue;
                    }
                    eamSopItemValueDTO.setResultValue(eamPointCheckDetail.getSopItemResult());
                    eamSopItemValueDTO.setId(eamPointCheckDetail.getSopItemValueId());
                    eamSopItemValueDTO.setStandardValue(eamPointCheckDetail.getSopItemValue());
                    eamSopItemDTO.setSaveValue(eamPointCheckDetail.getSopItemValueId());
                }
            }
        }
        return dto;
    }

    /**
     * 根据作业规程编号生成点检单
     *
     * @return StandardCodeDTO
     */
    public EamPointCheckResultDTO getSopStandard(EamPointCheckResultDTO dto) {
        //获取标准作业图片
        QueryWrapper<EamSopStandardImg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamSopStandardImg::getStandardId, dto.getId());
        List<EamSopStandardImg> list = eamSopStandardImgService.list(queryWrapper);
        dto.setImages(convertList(list, EamSopStandardImgDTO.class));

        //获取资产类型
        // EamAssetTypeDTO eamAssetTypeDTO = eamAssetTypeService.get(dto.getEquipTypeId());
        // dto.setAssetTypeCode(eamAssetTypeDTO.getAssetTypeCode());
        // dto.setAssetTypeName(eamAssetTypeDTO.getAssetTypeName());

        if (!StringUtils.isEmpty(dto.getAssetModelId())) {
//            EamAssetModelDTO eamAssetModelDTO = eamAssetModelService.get(dto.getAssetModelId());
//            dto.setModelNo(eamAssetModelDTO.getModelNo());
//            EamMakerDTO eamMakerDTO = eamMakerService.get(eamAssetModelDTO.getMakerId());
//            EamAssetBrandDTO eamAssetBrandDTO = eamAssetBrandService.get(eamAssetModelDTO.getBrandId());
//            dto.setMakerCode(eamMakerDTO.getMakerCode());
//            dto.setMakerName(eamMakerDTO.getMakerName());
//            dto.setMakerId(eamMakerDTO.getId());
//
//            dto.setBrandCode(eamAssetBrandDTO.getBrandCode());
//            dto.setBrandId(eamAssetBrandDTO.getMakerId());
//            dto.setBrandName(eamAssetBrandDTO.getMakerName());
        }

        //获取标准作业项
        EamSopItemQuery query = new EamSopItemQuery();
        query.setStandardId(dto.getId());
        List<EamSopItemDTO> eamSopItemDTOS = eamSopItemDao.queryList(query);

        List<String> ids = eamSopItemDTOS.stream().map(EamSopItemDTO::getId).collect(Collectors.toList());
        Map<String, List<EamSopItemValueDTO>> parentChildMap = new HashMap<>();
        // 查询条件
        if (ids.size() > 0) {
            QueryWrapper<EamSopItemValue> eamSopItemValueQueryWrapper = new QueryWrapper<>();
            eamSopItemValueQueryWrapper.lambda().in(EamSopItemValue::getSopItemId, ids);
            // 查询数据
            List<EamSopItemValue> eamSopItemValues = eamSopItemValueService.list(eamSopItemValueQueryWrapper);

            List<EamSopItemValueDTO> dtoList = convertList(eamSopItemValues, EamSopItemValueDTO.class);

            // 将节点按照父节点进行分组
            for (EamSopItemValueDTO node : dtoList) {
                String parentTypeId = node.getSopItemId();
                parentChildMap.computeIfAbsent(parentTypeId, k -> new ArrayList<>()).add(node);
            }

            for (EamSopItemDTO eamSopItemDTO : eamSopItemDTOS) {
                eamSopItemDTO.setDetails(parentChildMap.get(eamSopItemDTO.getId()));
            }
        }

        dto.setItemDTOS(eamSopItemDTOS);
        return dto;
    }


//    /**
//     * 根据作业规程编号生成点检单
//     *
//     * @param code 编号
//     * @return StandardCodeDTO
//     */
//    public EamPointCheckResultDTO info(String code) {
//        // 查询数据
//
//        return getSopStandard("",code);
//    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamSopStandardDTO>
     */
    public List<EamSopStandardDTO> getList(EamSopStandardQuery query) {
        // 查询数据
        if (StrUtil.isNotEmpty(query.getStandardCycleCode())) {
            String[] cycleValues = query.getStandardCycleCode().split("-");
            query.setStandardCycle(cycleValues[0]);
            query.setStandardCycleType(cycleValues[1]);
        }
        List<EamSopStandardDTO> list = this.baseMapper.getList(query);
        return list;
    }

    /**
     * 根据主键获取标准作业规程信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamSopStandard item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }

    /**
     * 获取标定标准列表
     *
     * @param assetKind
     * @param taskKind
     * @return
     */
    public List<EamSopStandardDTO> getStandardList(Integer assetKind, Integer taskKind, String equipTypeId) {
        List<EamSopStandardDTO> list = this.baseMapper.getStandardList(assetKind, taskKind, equipTypeId);
        return list;
    }

    /**
     * 获取作业周期
     *
     * @param sopTypeCode
     * @return
     */
    public List<DictionaryItemVo> getCheckPeriods(Integer assetKind, String sopTypeCode) {
        List<DictionaryItemVo> periods = new ArrayList<>();
        List<EamSopStandardDTO> list = this.baseMapper.getCheckPeriods(assetKind, sopTypeCode);

        for (EamSopStandardDTO sopStandardDTO : list) {
            DictionaryItemVo dictionaryItemVo = new DictionaryItemVo();
            dictionaryItemVo.setItemCode(sopStandardDTO.getStandardCycle() + "-" + sopStandardDTO.getStandardCycleType());
            String cycleUnit = sopStandardDTO.getStandardCycleType();
            switch (cycleUnit) {
                case "1":
                    cycleUnit = "时";
                    break;
                case "2":
                    cycleUnit = "日";
                    break;
                case "3":
                    cycleUnit = "个月";
                    break;
                case "4":
                    cycleUnit = "季";
                    break;
                case "5":
                    cycleUnit = "年";
                    break;
            }
            dictionaryItemVo.setItemName(sopStandardDTO.getStandardCycle() + cycleUnit);
            periods.add(dictionaryItemVo);
        }

        return periods;
    }
}

